package com.example.itcacp.controller;

import com.example.itcacp.dto.response.Result;
import com.example.itcacp.entity.Message;
import com.example.itcacp.entity.User;
import com.example.itcacp.service.MessageService;
import com.example.itcacp.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Resource
    private MessageService messageService;
    @Resource
    private UserService userService;

    // 获取用户消息列表
    @GetMapping("/list")
    public List<Message> getMessageList(
            @RequestParam Long userId,
            @RequestParam(required = false) String type) {

        if (type != null && !type.isEmpty()) {
            // 根据类型筛选消息
//            return messageService.getMessagesByUserIdAndType(userId, Message.MessageType.valueOf(type));

        }

        // 返回所有类型的消息
        return messageService.getMessagesByUserId(userId);
    }

    // 标记消息为已读
    @PostMapping("/markRead/{id}")
    public void markMessageAsRead(@PathVariable Long id) {
        messageService.markMessageAsRead(id);
    }

    // 搜索用户
    @GetMapping("/user/search")
    public User searchUser(@RequestParam String keyword) {
        // 实现用户搜索逻辑
        return userService.searchUsers(keyword);
    }

    // 获取联系人列表
    @GetMapping("/contacts")
    public Result getContacts(@RequestParam Long userId) {
        // 实现联系人列表获取逻辑
        List<User> contacts = messageService.getContacts ( userId );
        return Result.success (contacts);
    }

    // 获取聊天记录
    @GetMapping("/chat")
    public Result getChatMessages(
            @RequestParam Long senderId,
            @RequestParam(required = false) Long receiverId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            @RequestParam Message.MessageType messageType) {
        PageInfo<Message> chatMessages = messageService.getChatMessages ( senderId, receiverId, pageNum, pageSize, messageType);
        System.out.println (chatMessages);
        return Result.success (chatMessages);
    }

    // 标记某个发送者的消息为已读
    @PostMapping("/markReadBySender/{senderId}")
    public void markMessagesBySenderAsRead(
            @PathVariable Long senderId,
            @RequestParam Long receiverId) {

        messageService.markMessagesBySenderAsRead(senderId, receiverId);
    }

    // 获取各类未读消息数量
    @GetMapping("/unreadCount")
    public Map<String, Integer> getUnreadCount(@RequestParam Long userId) {
        return messageService.getUnreadCounts(userId);
    }
}